import Koa from 'koa'
import koaLogger from 'koa-logger'
import koaCors from 'koa2-cors'
import koaBodyparser from 'koa-bodyparser'
import koaOnerror from 'koa-onerror'

import ljwt from './lib/ljwt'
import appConfig from './configs/app' // 配置
import apiUri from './routers/api1' // api路由

import lauth from './middlewares/lauth'
import lapi from './middlewares/lapi'

// 实例化应用
const app = new Koa()

koaOnerror(app) // 错误拦截
app.on('error', (err, ctx) => {
  console.error(err)
})

// 中间件
app.use(koaLogger()) // 日志
app.use(koaCors({
  origin: ctx => ctx.url === '/login' ? '*' : 'http://localhost:8080',
  exposeHeaders: ['WWW-Authenticate', 'Server-Authorization'],
  maxAge: 5,
  credentials: true,
  allowMethods: ['HEAD', 'GET', 'POST', 'DELETE', 'PUT', 'PATCH', 'OPTIONS', 'CONNECT', 'TRACE'],
  allowHeaders: ['Content-Type', 'Authorization', 'Accept'],
})) // 跨域
app.use(lapi) // api响应JSON格式化
app.use(lauth) // 登录验证
app.use(koaBodyparser()) // 表单格式化

// api路由
app.use(apiUri.routes())

// 服务启动
app.listen(appConfig.port)
